package com.qf.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qf.annotation.ProccessInfo;
import com.qf.commons.TableData;
import com.qf.entity.Goods;
import com.qf.exception.BizException;
import com.qf.mapper.GoodsDao;
import com.qf.service.GoodsService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {
    private GoodsDao goodsDao;

    public GoodsServiceImpl(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }

    @Override
    public TableData<Goods> queryAll(Integer offset, Integer limit) throws BizException {
        TableData<Goods> tableData = new TableData<>();
        Page<Object> page=null;
        List<Goods> goodsList=null;
        try {
            page = PageHelper.offsetPage(offset, limit);

            goodsList  = goodsDao.queryAll();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("商品控制层错误："+e.getMessage());
        }

        if (goodsList.size()<0){
            return null;
        }
        tableData.setTotal(page.getTotal());
        tableData.setRows(goodsList);
        return tableData;
    }

    @Override
    @ProccessInfo(value = "修改商品信息", requireParamInfo = true)
    public Integer dynamicChange(Goods goods) throws BizException {
        Integer integer = 0;
        try {
            integer = goodsDao.dynamicUpdate(goods);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("服务层商品修改异常："+e.getMessage());
        }

        return integer;
    }

    @Override
    public Integer addGoods(Goods goods) {

        Integer integer = 0;
        try {
            integer = goodsDao.insert(goods);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("服务层添加商品异常："+e.getMessage());
        }

        return integer;
    }

    @Override
    public List<Goods> dynamicQuery(Goods goods) {
        List<Goods> goodsList = null;
        try {
            goodsList = goodsDao.dynamicQuery(goods);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("服务层根据id查询商品异常："+e.getMessage());
        }

        return goodsList;
    }

    @Override
    public TableData<Goods> queryGoodsCart(Integer uId) throws BizException {
        TableData<Goods> tableData = new TableData<>();
        List<Goods> goods=null;
        try {
            goods= goodsDao.queryGoodsCart(uId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("服务层根据id查询商品购物车异常："+e.getMessage());
        }

        if (goods.size()>0){
            tableData.setTotal((long) goods.size());
            tableData.setRows(goods);
        }

        return tableData;
    }
}
